package com.gzdh.tang.dishrecognition;


import sun.security.x509.X509CertImpl;

import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Enumeration;


/**
 * PKCS12证书中解析公钥、私钥、证书序列号
 * <p>
 * apiclient_cert.p12
 */
public class P12Utils {


    public void test() {
        // p12证书路径
        String path = "D:\\apiclient_cert.p12";
        P12InfoVo vo = this.parse(path, "1630436051");

        System.out.println("证书公钥: " + vo.getPublicKey());
        System.out.println("证书私钥: " + vo.getPrivateKey());
        System.out.println("证书序列号: " + vo.getSerialNo());
    }

    public static void main(String[] args) {

        String path = "D:\\apiclient_cert.p12";
        P12InfoVo vo = parse(path, "1451483202");
        System.out.println(vo);
        System.out.println("证书公钥: " + vo.getPublicKey());
        System.out.println("证书私钥: " + vo.getPrivateKey().toString());
        System.out.println("证书序列号: " + vo.getSerialNo());
    }

    /**
     * 解析p12文件
     *
     * @param p12Path 证书文件路径
     * @param passwd  证书密码 (也就是商户号)
     * @return
     */
    public static P12InfoVo parse(String p12Path, String passwd) {
        try {
            // 获取文件流
            FileInputStream is = new FileInputStream(p12Path);

            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(is, passwd.toCharArray());
            String keyAlias = null;
            //解析证书，必须有别名
            Enumeration<String> aliases = ks.aliases();
            if (aliases.hasMoreElements()) {
                keyAlias = aliases.nextElement();
            }
            //解析私钥
            PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, passwd.toCharArray());
            Certificate cert = ks.getCertificate(keyAlias);
            BigInteger serialNumber = ((X509CertImpl) cert).getSerialNumber();
            //证书一般都使用16进制表示
            String certSn = serialNumber.toString(16).toUpperCase();

            //设置证书公钥、私钥、序列号
            return P12InfoVo.builder()
                    .publicKey(cert.getPublicKey())
                    .privateKey(privateKey)
                    .serialNo(certSn)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}